﻿using Ivory.Libs;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Schism.libs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Schism.Mapping
{
    /// <summary>
    /// Tutorial: http://blog.josack.com/2011/08/my-first-2d-pixel-shaders-part-3.html
    /// </summary>
    public sealed class LightingEngine
    {
        //Fields
        private Texture2D _AmbientLightTexture;
        public RenderTarget2D _LightingBuffer;

        //ctor
        public LightingEngine()
        {

        }
        
        //Methods
        public void CreateLightingMap(params ILight[] lights)
        {
            if (_AmbientLightTexture == null)
                _AmbientLightTexture = TextureBuilder.CreateTexture(ObjectHolder.GameObject.GraphicsDevice,
                    ObjectHolder.GameObject.GraphicsDevice.Viewport.Width,
                    ObjectHolder.GameObject.GraphicsDevice.Viewport.Height, Color.White, 0x32);

            _LightingBuffer = new RenderTarget2D(ObjectHolder.GameObject.GraphicsDevice,
                    ObjectHolder.GameObject.GraphicsDevice.Viewport.Width,
                    ObjectHolder.GameObject.GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.None);

            ObjectHolder.GameObject.GraphicsDevice.SetRenderTarget(_LightingBuffer);
            ObjectHolder.GameObject.GraphicsDevice.Clear(new Color(0x00, 0x00, 0x00, 0xff));

            using (SpriteBatch lightingBatch = new SpriteBatch(ObjectHolder.GameObject.GraphicsDevice))
            {
                lightingBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);


                lightingBatch.Draw(_AmbientLightTexture, new Vector2(0, 0), Color.White);

                lightingBatch.End();
            }

            ObjectHolder.GameObject.GraphicsDevice.SetRenderTarget(null);
        }

        public void RenderLightingMap(SpriteBatch batch, params Texture2D[] textureToLight)
        {
            batch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
            ResourceBank.Get<Effect>("LightingFx").Parameters["lightMask"].SetValue(_LightingBuffer);
            ResourceBank.Get<Effect>("LightingFx").CurrentTechnique.Passes[0].Apply();

            foreach (Texture2D texture in textureToLight)
                batch.Draw(texture, new Vector2(0, 0), Color.White);

            batch.End();
        }
    }
}
